package com.wstuo.common.exchange;

import java.net.URISyntaxException;
import java.util.List;

import org.apache.log4j.Logger;

import com.moyosoft.exchange.Exchange;
import com.moyosoft.exchange.ExchangeServiceException;
import com.moyosoft.exchange.folder.ExchangeFolder;
import com.moyosoft.exchange.folder.FolderType;
import com.wstuo.common.tools.dto.EmailDTO;
import com.wstuo.common.tools.dto.EmailMessageDTO;
import com.wstuo.common.tools.dto.EmailServerDTO;
/**
 * com.moyosoft.exchange.Exchange 收费工具
 * （该jar一直都被引用，但是碍于收费版本，因此不使用）
 * @author gs60
 */
public class MoyosoftExchangeService implements IWebDavService {

	private static final String HOST_TYPE_HTTPS = "https://";
	private static final String HOST_TYPE_HTTP = "http://";
	private static final Logger LOGGER = Logger.getLogger(MoyosoftExchangeService.class);
	@Override
	public boolean emailConnTest(EmailServerDTO emailServerDTO) {
		try {
			Exchange exchange = createExchangeService(emailServerDTO);
			if (exchange != null) {
				ExchangeFolder folder = exchange.getFolder( FolderType.Inbox );
				if (folder != null) {
					return true;
				}
			}
		} catch (Exception e) {
			LOGGER.error(e);
		}
		return false;
	}

	@Override
	public List<EmailMessageDTO> getInboxMail() {
		return null;
	}

	@Override
	public boolean sendEmail(EmailDTO dto) {
		return false;
	}

	private Exchange createExchangeService(EmailServerDTO dto) throws URISyntaxException, ExchangeServiceException{
		Exchange exchange = null;
		if (dto != null ) {
			boolean useHttps = false;
			String host = dto.getExchangeHostName();
			if (host.indexOf(HOST_TYPE_HTTPS) > -1) {
				useHttps = true;
				host = host.replace(HOST_TYPE_HTTPS, "");
			}else if(host.indexOf(HOST_TYPE_HTTP) > -1){
				host = host.replace(HOST_TYPE_HTTP, "");
			}
			exchange = new Exchange( host , dto.getExchangeUserName()
					, dto.getExchangePassword() , dto.getDomain(), useHttps);
		}
		return exchange;
	}
}
